package com.hbird.controller;

import com.hbird.dao.UserRepository;
import com.hbird.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 *
 * JPA测试Controller
 * 实体类 User
 *
 * 易犯错误：Controller标签是@Controller而不是@RestController，
 *
 * 不然也会直接返回字段值
 */
@Controller
@RequestMapping(value = "jpa")
public class JPATestController {
    @Autowired
    UserRepository userRepository;

    /**
     * test
     * @param modelMap
     * @return
     */
    @RequestMapping("/test")
    public String jpaTest(ModelMap modelMap){
        userRepository.save(new User("codepython","123456","xxxxx@126.com"));
        List<User> users = userRepository.findAll();
        modelMap.put("users", users);
        return "jpatest";
    }





    /**
     * 输出字符串测试
     * http://localhost:8080/helloboot
     * @return
     */
    @RequestMapping("/hellotest")
    public String helloTest(){
        return "Hello！";
    }

    /**
     * htmltest
     * @return
     */
    @RequestMapping("/htmltest")
    public String test(){
        return "login";
    }

    /**
     * 测试 Model
     * spring自动为Model创建实例，并作为controller的入参
     * @param model
     * @param name
     * @return
     */
    @RequestMapping("/modeltest")
    public String testVelocity(Model model, String name){
        if (name==null ||name.isEmpty()){
            name ="您没有输入名字！";
        }
        model.addAttribute("name", name);
        return "modeltest";
    }

    /**
     * 测试 ModelAndView
     * @param name
     * @return
     */
    @RequestMapping("modelandview")
    public ModelAndView testModel(String name) {
        if (name==null ||name.isEmpty()){
            name =" 您没有输入名字！";
        }
        //构建ModelAndView实例，并设置跳转地址
        ModelAndView view = new ModelAndView("modelandviewtest");
        //将数据放置到ModelAndView对象view中,第二个参数可以是任何java类型
        view.addObject("name", name);
        //返回ModelAndView对象view
        return view;
    }

}